import json
import random

import redis
import requests


def get_random_code(length=6):
    """生成指定长度的随机验证码"""
    return ''.join(random.choices('0123456789', k=length))


def send_code_by_sms(tel, code):
    """通过短消息服务器发送验证码"""
    resp = requests.post(
        url='http://sms-api.luosimao.com/v1/send.json',
        auth=('api', 'key-c6305c397d86ab1093b46ad228e5a3fb'),
        data={
            'mobile': tel,
            'message': f'您的短信验证码是{code}，打死也不能告诉别人哟！【Python小课】'
        },
        timeout=10,
        verify=False
    )
    return json.loads(resp.text)


tel = input('请输入手机号: ')
code = get_random_code()
cli = redis.Redis(host='120.77.222.217', password='1qaz2wsx')
if cli.get(f'block:{tel}'):
    print('请不要在120秒内重复发送短信验证码!!!')
    cli.incr(f'block:{tel}')
else:
    result = send_code_by_sms(tel, code)
    if result['error'] == 0:
        print('短信验证码发送成功!')
        cli.set(f'valid:{tel}', code, ex=600)
        cli.set(f'block:{tel}', 1, ex=120)
cli.close()
